package com.gy.def.utils;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

@SuppressWarnings("unused")
public class StrUtil {

    /**
     * 将字符串的编码格式转换为utf-8
     *
     * @param str 字符串
     * @return Name = new
     * String(Name.getBytes("ISO-8859-1"), "utf-8");
     */
    static String toUTF8(String str) {
        if (isEmpty(str)) {
            return "";
        }
        try {
            if (str.equals(new String(str.getBytes("GB2312"), "GB2312"))) {
                str = new String(str.getBytes("GB2312"), StandardCharsets.UTF_8);
                return str;
            }
        } catch (Exception ignored) {
        }
        try {
            if (str.equals(new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.ISO_8859_1))) {
                str = new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                return str;
            }
        } catch (Exception ignored) {
        }
        try {
            if (str.equals(new String(str.getBytes("GBK"), "GBK"))) {
                str = new String(str.getBytes("GBK"), StandardCharsets.UTF_8);
                return str;
            }
        } catch (Exception ignored) {
        }
        return str;
    }

    /**
     * 判断是否为空
     *
     * @param str 字符串
     * @return 是否为空
     */
    public static boolean isEmpty(String str) {
        // 如果字符串不为null，去除空格后值不与空字符串相等的话，证明字符串有实质性的内容
        return str == null || str.trim().isEmpty();
    }

    public static List<String> getListToString(String str) {
        return Arrays.asList(str.split(","));
    }

    public static String getStringToList(List<String> strList) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < strList.size(); i++) {
            str.append(strList.get(i));
            if (i < strList.size() - 1) {
                str.append(",");
            }
        }

        return str.toString();
    }

    /**
     * 倒置字符串
     *
     */
    public static String reverseString(String s) {
        char[] word = s.toCharArray();
        int i = 0;
        int j = s.length() - 1;
        while (i < j) {
            char temp = word[i];
            word[i] = word[j];
            word[j] = temp;
            i++;
            j--;
        }
        return new String(word);
    }

}
